<template>
  <div id="resourceManagement">
    <div id="tabelTitle">
      角色管理
    </div>
    <div id="table">
      <avue-crud
        ref="crud"
        v-model="form"
        :search.sync="searchForm"
        :page.sync="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
        :before-close="beforeClose"
        @selection-change="selectionChange"
      >
        <template slot="menuLeft" slot-scope="{size}">
          <el-button type="primary" :size="size" @click="rowDel()">删除</el-button>
        </template>
        <template slot="menu" slot-scope="{row,size}">
          <el-button type="primary" :size="size" @click.stop="handleEdit(row)">查看</el-button>
        </template>


        <template slot-scope="scope" slot="menuListForm">
          <el-tree
            :data="treeData"
            ref="tree"
            show-checkbox
            node-key="menuId"
            :default-checked-keys="cheacklist"
            :props="defaultProps">
          </el-tree>
        </template>

      </avue-crud>
    </div>
  </div>
</template>

<script>
import tableMixins from "@/mixins/tableMixin.vue"

export default {
  name: "roleManagement",
  mixins: [tableMixins],
  data() {
    return {
      dialogVisible: false,
      form: {},
      //访问接口前缀


      url: "yuanjiu.testnew/yj-role",
      searchForm: {},
      // 表格参数
      tableOption: {
        border: true,
        index: false,
        indexLabel: '序号',
        indexWidth: 50,
        stripe: true,
        align: 'center',
        searchMenuSpan: 8,
        searchLabelWidth: 100,
        calcHeight: 300,
        dialogWidth: 900,
        menuWidth: 200,
        menu: true,
        menuAlign: 'center',
        refreshBtn: false,
        columnBtn: false,
        searchShowBtn: false,
        addBtn: true,
        selection: true,
        rowKey: "id",
        emptyBtn: true,
        editBtn: false,
        viewBtn: false,
        delBtn: false,
        emptyBtnText: "重置",
        editBtnText: "修改",
        maxHeight: 645000,
        searchSize: "medium",
        column: [
          {
            prop: 'roleName',
            label: '角色名称',
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入角色名称",
              trigger: "blur"
            }],

          }, {
            prop: 'roleDesc',
            label: '描述',
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入描述",
              trigger: "blur"
            }],
          }, {
            prop: 'adminRealNames',
            label: '角色成员',
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入角色成员 ",
              trigger: "blur"
            }],

          }, {
            prop: 'roleStatus',
            label: '状态',
            type: "select",
            props: {
              label: 'name',
              value: 'code'
            },
            dicData: [{
              name: '有效',
              code: 1
            }, {
              name: '禁用',
              code: 2
            }],
            rules: [{
              required: true,
              message: "请选择状态 ",
              trigger: "change"
            }],
          },
          {
            prop: 'menuList',
            label: '菜单权限',
            type: "tree",
            formslot: true,
            labelslot: true,
            errorslot: true,
            hide: true,
          },
        ]
      },
      listUrl: 'pageYjRole',
      delUrl: "deleteList",
      updateUrl: "insertOrUpdate",
      delIdList: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuIds: [],
      cheacklist:[],
      newList:[]
    }
  },
  methods: {
    //勾选获取当前数据ID
    selectionChange(list) {
      // console.log(list)
      this.delIdList = []
      list.forEach((x) => {
        this.delIdList.push(x.roleId)
      })
    },

    /**
     * 获取列表数据
     */
    getList() {
      this.tableLoading = true;
      let query = Object.assign({}, this.searchForm, this.page, this.search);
      query.current = this.page.currentPage
      query.size = this.page.pageSize
      this.$httpService.post("/" + this.url + "/" + this.listUrl, query).then(res => {
        this.tableData = res.records
        this.page.total = res.total;
        this.tableLoading = false
      })
    },


    /**
     * 新增保存
     * @param row 行数据
     * @param done 完成回调
     * @param loading 加载回调
     */
    handleSave: function (row, done, loading) {

      let menuId = this.$refs.tree.getHalfCheckedKeys()

      row.menuIds = menuId
      this.$httpService.post("/" + this.url + "/" + this.addUrl, row).then(res => {
        this.$message.success('新增成功');
        this.getList();
        done();
        loading();
      }).catch(res => {
        loading();
      })
    },


    /**
     * 修改保存
     * @param row 行数据
     * @param index 行索引
     * @param done 完成回调toggleSelection
     * @param loading 加载回调
     */
    handleUpdate: function (row, index, done, loading) {
      // console.log('row', row)
      delete row.createTime
      delete row.menuIdList
      delete row.menuName
      row.menuIds =[]
      let menuId =  this.$refs.tree.getCheckedNodes().concat(this.$refs.tree.getHalfCheckedNodes());
      // console.log('menuIdmenuId', menuId)
      menuId.forEach((x)=>{
        row.menuIds.push(x.menuId)
      })
      // console.log('3333333333',row)
      done();
      this.$httpService.post("/" + this.url + "/"+this.updateUrl, row).then(res => {
        this.$message.success('修改成功');
        this.getList();
        done();
        loading();
      }).catch(res=>{
        loading();
      })
    },
    /**
     * 删除
     * @param row 行数据
     * @param index 行索引
     */
    rowDel: function (row) {
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$httpService.post("/" + this.url + "/" + this.delUrl, this.delIdList).then(res => {
          this.$message.success('删除成功');
          this.getList();
        })
      })
    },

    //树状菜单
    getCaidan() {
      this.$httpService.post(' /yuanjiu.testnew/yj-menu/listYjMenu').then(res => {
        this.treeData = this.getMenuList(res)
      })
    },
    //递归树状菜单
    getMenuList(authList) {
      let menu = [];
      let map = {}
      authList.forEach(m => {
        m.children = [];
        map[m.menuId] = m; // {1:菜单,2:菜单}
        if (m.menuParentId === -1) {
          menu.push(m); // 如果是根 就直接push到menu中
        } else {
          map[m.menuParentId] && map[m.menuParentId].children.push(m);
        }
      });
      return menu
    },
    // 查找一个树多有第一个节点，深度遍历
    /* 代码 */

    getCList(data){
      data.forEach((x)=>{
        if(x.children&&x.children.length!==0){
          this.getCList(x.children)
        }
        else {
          this.newList.push(x.menuId)
        }
      })
    },


    //自定义修改
    handleEdit(row) {
      this.getCList(this.treeData)
      if(row.menuList&&row.menuList.length>0){

      row.menuList.forEach((x)=>{
        this.newList.forEach((y)=>{
          if(x.menuId == y){
            this.cheacklist.push(y)
          }
        })
      })
      }

      setTimeout(() => {
        if (this.$refs.crud) {
          this.$refs.crud.rowEdit(row)
        }
      }, 200)

    },
    beforeClose(done, type) {
      this.cheacklist = []
      done()
    },
  },
  mounted() {
    this.getCaidan()
  }
}
</script>

<style scoped>

</style>
